package com.fivestar.pmanager.web.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fivestar.pmanager.constants.CommonConstants;
import com.fivestar.pmanager.service.FsUserService;

public class MyUsernamePasswordAuthenticationFilter extends
        UsernamePasswordAuthenticationFilter
{
    private static final Logger logger = LoggerFactory.getLogger(MyUsernamePasswordAuthenticationFilter.class);
    
    private FsUserService fsUserService;
    public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "lastLoginId";
    public static final String SESSION_KEY_SUPPORT_USER          = "user";
    public static final String SESSION_KEY_COMMON_PARAMTER       = "COMMON_PARAMTER";

    private boolean postOnly = false;
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException
    {
        HttpSession session = request.getSession();
        if (this.postOnly && !request.getMethod().equals("POST"))
        {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " +
                            request.getMethod());
        }
        else
        {
            String loginId = request.getParameter("loginId");
            String loginPwd = request.getParameter("loginPwd");
            request.setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, loginId);

            validateNull(loginId, loginPwd, session);

            MyUsernamePasswordAuthenticationToken authRequest = new MyUsernamePasswordAuthenticationToken(
                    loginId, loginPwd);
            authRequest.setRequest(request);
            logger.info("====={}",authRequest);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    /**
     * 验证数据是否为空
     */
    private void validateNull(String loginId, String loginPwd, HttpSession session)
    {
        if(loginId == null || loginId.equals(""))
        {
            increaseErrorTime(session);
            throw new AuthenticationServiceException("用户名不能为空!");
        }

        if(loginPwd == null || loginPwd.equals(""))
        {
            increaseErrorTime(session);
            throw new AuthenticationServiceException("登录密码不能为空!");
        }
    }

    public FsUserService getfsUserService()
    {
        return fsUserService;
    }


    public void setfsUserService(FsUserService fsUserService)
    {
        this.fsUserService = fsUserService;
    }


    public boolean isPostOnly()
    {
        return postOnly;
    }


    @Override
    public void setPostOnly(boolean postOnly)
    {
        this.postOnly = postOnly;
    }

    private void increaseErrorTime(HttpSession session)
    {
        Integer errorTime = (Integer) session.getAttribute("errorTime");
        if(errorTime == null) errorTime = 0;
        errorTime++;
        session.setAttribute("errorTime", errorTime);
    }

    private void clearErrorTime(HttpSession session)
    {
        session.setAttribute("errorTime", 0);
    }


    private int getErrorTime(HttpSession session)
    {
        Integer errorTime = (Integer) session.getAttribute("errorTime");
        if(errorTime == null) errorTime = 0;
        return errorTime;
    }
}
